package com.xyauto.theme.network

import com.xyauto.theme.App
import com.xyauto.theme.BuildConfig
import com.xyauto.theme.network.interceptor.OfflineCacheInterceptor
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

/**
 * Created by gongziyi on 2021/5/13 17:58.
 */
object ApiHelper {

    private const val CONNECT_TIMEOUT = 15L
    private const val READ_TIMEOUT = 15L
    private const val WRITE_TIMEOUT = 15L
    private const val DEFAULT_HTTP_CACHE_SIZE = 1024 * 1024 * 20L //MB


    fun getRetrofit(url: String): Retrofit {
        return Retrofit.Builder()
            .baseUrl(url) //基本的url
            .addConverterFactory(GsonConverterFactory.create()) //使用gson
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//使用rxjava
            .client(getOkHttpClient())
            .build()
    }

    private fun getOkHttpClient() = OkHttpClient.Builder()
        .retryOnConnectionFailure(true)
        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
        .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
        .addInterceptor(
            HttpLoggingInterceptor().setLevel(
                if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
            )
        )
        .addNetworkInterceptor(OfflineCacheInterceptor())
//        .addNetworkInterceptor(TimeCacheInterceptor())
        .cache(Cache(File(App.instance.cacheDir, "responses"), DEFAULT_HTTP_CACHE_SIZE))
        .build()
}